package cn.jinjimi.app.poster.presenter;

import cn.jinjimi.app.controller.event.NoticeEvent.NoticeEvent;
import cn.jinjimi.app.controller.event.NoticeEvent.NoticeNewPosterEvent;
import cn.jinjimi.domain.data.dto.PosterTemplateDto;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.store.PosterStore;
import cn.jinjimi.app.managers.NoticeManager;
import cn.jinjimi.app.poster.bean.PosterTemplate;
import cn.jinjimi.app.poster.fragment.PosterContainerFragment;
import cn.jinjimi.app.poster.interfaces.PosterActivityView;
import cn.jinjimi.app.presenter.NetBasePresenter;
import cn.jinjimi.app.store.entity.NoticeEntity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;

/**
 * Created by lforxeverc on 16/9/27.
 */

public class PosterHomePresenter extends NetBasePresenter {
    PosterActivityView mView;
    int loadType = PosterContainerFragment.DataType.INFORMATION_POSTER;

    public PosterHomePresenter(PosterActivityView view) {
        super(view);
        mView = view;
    }

    public void setLoadType(int loadType) {
        this.loadType = loadType;
    }

    public void loadCategory(final int categoryCode) {
        NoticeManager.getNoticesByCode(loadType == PosterContainerFragment.DataType.JINJU_POSTER ? NoticeEntity.TypeNewJinju : NoticeEntity.TypeNewPoster);
        Task.callInBackground(new Callable<PosterTemplateDto>() {
            @Override
            public PosterTemplateDto call() throws Exception {
                return ServiceManager.getService(PosterStore.class).fetchTemplatesCategories(categoryCode);
            }
        }).continueWith(new Continuation<PosterTemplateDto, Void>() {
            @Override
            public Void then(Task<PosterTemplateDto> task) throws Exception {
                PosterTemplateDto templates = task.getResult();
                if (templates != null && templates.data != null) {
                    List<PosterTemplate> templateList = templates.data;
                    mView.loadSuccess(templateList);
                    return null;
                } else {
                    mView.showError();
                }
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoticeNewPosterEvent(NoticeNewPosterEvent event) {
        if (event.state == NoticeEvent.StateAdd) {
            mView.setRedInfo(event.noticePosterDTO);
        }
    }
}
